package com.chuangyang.fixboxmaster.ui.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxmaster.BuildConfig;
import com.chuangyang.fixboxmaster.bean.VerifyCodeEvent;

import de.greenrobot.event.EventBus;

/**
 * Created by vanshu on 15/3/24 10:22.
 */
public class SMSReceiver extends BroadcastReceiver {

    // 增加指定来电号码到过滤和增加短信内容到截取
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Object messages[] = (Object[]) bundle.get("pdus");
        if(messages==null){
            return ;
        }
        SmsMessage smsMessage[] = new SmsMessage[messages.length];
        for (int n = 0; n < messages.length; n++) {
            smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
        }
        if(smsMessage[0].getOriginatingAddress().equals("10690570570610170")){ //TODO 号码同样可能失效
            if (BuildConfig.DEBUG) {
                Toast.makeText(context, "Received SMS: " + smsMessage[0].getOriginatingAddress() + ",内容为：" + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG).show();
            }
            String content = smsMessage[0].getMessageBody();
            String number =StringUtils.getNumberFromString(content);
            VerifyCodeEvent verifyCodeEvent = new VerifyCodeEvent();
            verifyCodeEvent.code = number;//TODO 获取校验码的规则可能失效，如果未来失效，需要及时更新
            if(StringUtils.validateNumber(verifyCodeEvent.code)){
                EventBus.getDefault().post(verifyCodeEvent);
            }
        }
    }


}